package com.zyd.controller.login;

import com.google.common.collect.Maps;
import com.zyd.constants.ErrorDef;
import com.zyd.exception.BusinessException;
import com.zyd.io.model.UserEntity;
import com.zyd.io.vo.page.MultiQueryPageVO;
import com.zyd.io.vo.res.ResBody;
import com.zyd.io.vo.user.LoginRequestVO;
import com.zyd.io.vo.user.ModifyPasswdVO;
import com.zyd.io.page.PageBean;
import com.zyd.io.vo.user.UserVO;
import com.zyd.service.user.UserService;
import com.zyd.util.MD5Utils;
import com.zyd.util.ToolUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;

import com.zyd.pojo.User;
import com.zyd.service.login.LoginService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


@RestController
@RequestMapping("/")
public class LoginController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private HttpSession session;

    @Autowired
    private UserService service;

    private final static Logger LOGGER = LoggerFactory.getLogger(LoginController.class);


    @RequestMapping(value = "/getCode", method = RequestMethod.POST)
    public ResBody getCode(@RequestBody Map mobiles) {
        try {
            //去除字符串中的空格、回车、换行符、制表符等
            String mobile2 = replaceSpecialStr((String) mobiles.get("mobile"));
            mobile2 = service.findMobilebyusername(mobile2);
            String code = loginService.getCode(mobile2);
            service.setValidatecode(mobile2, code);
            //session.setAttribute(mobile2,code);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResBody(ErrorDef.SYSTEM_ERROR, e.getMessage());
        }
        return new ResBody(ErrorDef.SUCCESS, "发送短信成功");
    }

    /**
     * 用户登录
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)


    public ResBody login(@RequestBody Map<String, String> map) {
        try {
            String username = map.get("username");
            if (StringUtils.isEmpty(username)) {//如果没有username
                throw new RuntimeException("请输入正确的用户名");
            }
            String password = map.get("password");
            if (StringUtils.isEmpty(password)) {//如果没有password
                throw new RuntimeException("请输入正确的密码");
            }
            if (!isSpecialUser(username)) {
                String code = map.get("code");
                if (StringUtils.isEmpty(code)) {//如果没有验证码
                    throw new RuntimeException("请输入验证码");
                }
                //用手机号获取
                username = service.findMobilebyusername(username);
                String s = service.findValidatecode(username);
                System.out.println(s);
                if (StringUtils.isEmpty(s)) {//session中获取系统验证码
                    throw new RuntimeException("请先获取验证码");
                }
                String[] split = s.split("&");
                Long codeTime = Long.parseLong(split[1]);
                long nowTime = new Date().getTime();
                if (nowTime - codeTime > 5 * 60 * 60 * 1000) {//过期时间为5分钟
                    session.removeAttribute(username);
                    throw new RuntimeException("验证码超时");
                }
                String sysCode = split[0];
                if (!sysCode.equals(code)) {//两个验证码不一致
                    throw new RuntimeException("验证码不正确");

                }
            }
            //移除验证码
            //session.removeAttribute(username);

            LoginRequestVO requestVO = new LoginRequestVO();
            requestVO.setUsername(username);
            requestVO.setPasswd(password);

            ResBody resBody = new ResBody(ErrorDef.SUCCESS, "登录成功");
            Map<String, Object> ret = service.login(requestVO, session);
            resBody.setData(ret);
            return resBody;
        } catch (BusinessException e) {
            return new ResBody(e.getCode(), e.getMessage());
        } catch (Exception e) {
            LOGGER.error("", e);
            return new ResBody(ErrorDef.SYSTEM_ERROR, "登录失败");
        }
    }

    /**
     * 去除字符串中的空格、回车、换行符、制表符等
     *
     * @param str
     * @return
     */
    private static String replaceSpecialStr(String str) {
        String repl = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            repl = m.replaceAll("");
        }
        return repl;
    }

    private boolean isSpecialUser(String username) {
        String[] users = {"13844666059", "admin","zhangsan"};
        for (String user : users) {
            if (user.equals(username)) {
                return true;
            }
        }
        return false;
    }

}
